package com.atguigu.jucdemo.interactive;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
 * 多线程之间按顺序调用，实现A->B->C
 * 三个线程启动，要求如下：
        *  *  *
        * AA打印5次，BB打印10次，CC打印15次
 * 接着
 * AA打印5次，BB打印10次，CC打印15次
 * ......来10轮
 *  *
         *
         *  笔记：Java里面如何进行工程级别的多线程编写
 *  * 1 多线程变成模板（套路）
        *  *  高内聚低耦合前提下，线程    操作    资源类
 *  *  *
         *    2 判断   干活   通知
 *  *  *
         *    3 多线程通信中，如果存在wait方法的调用要避免，------虚假唤醒
 */
public class ThreadOrderAccess {
    public static void main(String[] args) {
        ShareData shareData = new ShareData();

        new Thread(()-> {
                for (int i = 0; i < 10; i++) {
                    shareData.print5();
                }
            }
        ).start();

        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                shareData.print10();
            }
        }
        ).start();

        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                shareData.print15();
            }
        }
        ).start();
    }
}
class ShareData {
    private int flag = 1;
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    public void print5(){
        lock.lock();
        try {
            while(flag!=1){
                condition1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println("AA"+"\t"+(i+1));
            }
            flag=2;
            condition2.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }

    }
    public void print10(){
        lock.lock();
        try {
            while(flag!=2){
                condition2.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println("BB"+"\t"+(i+1));
            }
            flag=3;
            condition3.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    public void print15(){
        lock.lock();
        try {
            while(flag!=3){
                condition3.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println("CC"+"\t"+(i+1));
            }
            flag=1;
            condition1.signal();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
